<template>
  <div id="cart">
    <!-- <nav-bar title="购物车" /> -->
    <div class="pay-detail" :style="isBack">
      <ul>
        <li class="p-list" v-for="(shop, index) in shopCart" :key="index">
          <!-- 单选框 -->
          <mt-switch v-model="shop.isSelected"></mt-switch>
          <img :src="shop.thumb_path" alt="">
          <div class="pay-calc">
            <p>{{shop.title}}</p>
            <div class="calc">
              <span>￥ {{shop.sell_price}}</span>
              <div class="number-li">
                <span @click="substract(shop)">-</span>
                <span>{{shop.num}}</span>
                <span @click="addNum(shop)">+</span>
              </div>
            </div>
            <a href="javascript:void(0);" @click="del(shop, index)" class="delete">删除</a>
          </div>
        </li>
      </ul>
    </div>

    <div class="show-price">
      <div class="show-1">
        <p>已选择商品 {{payment.count}} 件</p>
        <span>总计（不含运费）： <strong>￥ {{payment.total}} 元</strong></span>
      </div>
      <a href="javascript:void(0);" class="close-account">结算</a>
    </div>
  </div>
</template>

<script>
/* 导入 处理购物车 js文件  */
import GoodsTool from "@/GoodsTool.js";


export default {
  name: "Cart",

  data() {
    return {
      shopCart: [],
      /* 购物车是否为空 样式 */
      back_null: {
        backgroundImage: "url(" + require("../../assets/shopCart_null.png") + ")",
        backgroundRepeat: "no-repeat",
        backgroundSize: "100% auto",
        height: "500px"
      },
      back_raw: {
        background: "none"
      },
      isBack: this.back_null
    }
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`

    let res = confirm("确定要离开吗？？？");

    if(res){
      // 保存用户编辑的数据
      let obj = {};
      this.shopCart.forEach((shop)=>{
        obj[shop.id] = shop.num;
      });
      GoodsTool.saveGoods(obj);

      next();
    }else{
      next(false); //取消导航
    }
  },
  computed:{
    payment(){
      // 默认只有 get 方法
      let total = 0; // 总价格
      let count = 0; // 总个数

      this.shopCart.forEach(shop=>{
        // 如果 勾中
        if(shop.isSelected){
          count += shop.num;
          total += shop.num * shop.sell_price;
        }
      });

      return{
        total, count
      };
    }
  },
  methods:{
    // 删除
    del(shop, index){
      // 删除数组元素
      this.shopCart.splice(index, 1);
      // 删除本地储存对应的 id
      GoodsTool.delete(shop.id);
      /* 如果购物车为空 改变背景 */
      if(Object.keys(GoodsTool.getGoodsList()).length === 0){
        this.isBack = this.back_null;
      }
      // vuex 修改购物车角标
      this.$store.getters.getShopNum;
    },
    // 数量 ++
    addNum(shop){
      shop.num ++;
      this.$store.dispatch('addShopNumByAction', 1);

    },
    // 数量 --
    substract(shop){
      if(shop.num <= 1){
        return;
      }
      shop.num --;
      this.$store.dispatch('addShopNumByAction', -1);

    }
  },
  created(){
    // console.log(GoodsTool.getGoodsList());
    let goodsList = GoodsTool.getGoodsList();
    // {"1": 5, "2": 8}
    // let ids = Object.keys(goodsList).join(',');
    let ids = Object.keys(goodsList);
    let temp = ids.map(item => `id=${item}`).join('&');
    // console.log(temp);
    if(ids){
      // 发起请求 获取用户购物商品的列表
      this.$axios.get(`goods/geetshopcarlist?${temp}`)
      .then(res=>{
        // console.log(res.data);
        /* 如果购物车是空的 */
        if(res.data === "null"){
          // console.log("购物车是空的");
          this.isBack = this.back_null;
          return;
        }
        /* 否则  背景图片为空 */
        this.isBack = this.back_raw;
        // console.log(res.data === "null");
        this.shopCart = res.data;

        // vue 会将 shopCart 对象的所有属性进行监视， 完成响应式
        /* object.defineProperty ( this, 'shopCart',{ 
          set:function(){ 判断shopcart元素是否有属性 */
        // 给数组元素添加属性
        this.shopCart.forEach(val=>{
          let shop_id = goodsList[val.id];
          if(shop_id){

            /* 如果数据不完成的情况下要添加属性 ，
             就需要手动通知vue => 双向数据绑定 */
            this.$set(val, 'num', shop_id);
            this.$set(val, 'isSelected', true);
            /* val.num = shop_id;
            // 设置是否选中
            val.isSelected = true; */
          }
        });
        // console.log(this.shopCart);
      })
      .catch(err=>{
        console.log('购物商品获取失败：', err);
      })
    }
  }
};
</script>

/* // 这里的 scoped 表示只在当前组件起作用 （局部） */
<style lang="css" scoped>
#cart{
  width: 100%;
  height: 100%;
}
.pay-detail {
  width: 100%;
  margin-bottom: 108px;
}
.pay-detail img{
  display: inline-block;
  width: 30%;
  /* margin-left: 3%;
  margin-top: 3%; */
}
.pay-detail ul li {
  display: flex;
  justify-content: space-around;
  align-content: center;
  padding: 5px;
  background-color: #ddf;
  margin-bottom: 5px;
  /* 超出隐藏 省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.pay-calc{
  width: 45%;
  padding: 5px;
  border: 1px solid #dff;
  border-radius: 5px;
  background-color: rgb(236, 236, 236);
  position: relative;
}
.calc {
  position: absolute;
  bottom: 5px;
  padding: 5px;
}
.calc > span {
  display: block;
  color: rgb(255, 59, 59);
  margin-bottom: 20px;
}
.number-li span{
  display: inline-block;
  padding: 2px 8px;
  border: 1px solid #888;
  border-radius: 5px;
  margin-right: 3px;
  font-weight: bold;
}
.number-li span:nth-child(2){
  width: 30px;
  text-align: center;
}
.delete {
  position: absolute;
  bottom: 5px;
  right: 5px;
  font-size: 12px;
  color: brown;
}

.show-price {
  width: 90%;
  padding: 5px 5%;
  background-color: #ccc;
  position: fixed;
  bottom: 55px;
}
.show-price span {
  font-size: 14px;
  color: #666;
}
.show-price span strong {
  color: rgb(172, 0, 0);
}
.close-account{
  position: absolute;
  right: 5px;
  top: 10px;
  color: #fff;
  background-image: linear-gradient(to top, rgb(255, 60, 0), orange) ;
  border-radius: 20px;
  padding: 5px 20px;
}
</style>

<style>
.mint-switch {
  width: 15%;
}
</style>